Implementation advice

I recommend implementing the features in the order below. I have added a few additional implementation tips.

1 Arbitrary print statements

This feature can be a tiny bit trickier than it seems.

Parsing

I recommend to start by implementing the grammar on the previous page, minus input, conditionals, and loops. In other words, change programs to be a sequence of statements, where each statement can be either printString, printNumber, or an assignment.

Emitting

WarningUse .asciz!

I led us astray when I recommended that we use .ascii to define string constants.

Because we pass our strings to a C library function, we should use .asciz instead. This directive defines a null-terminated string, also known as a C-string. This kind of string is what the C library functions expect.

The trickiest part of this feature is that the compiler must be able to emit an arbitrary number of printString statements.

Each string constant needs its own unique label. Consider using a similar technique that we used for variables: Use the compiler’s state to generate unique labels, and keep a map from string-constant to label.

2 Input

In your C runtime, implement a function that can read a number. The scanf function can help!

3 Conditionals

Parsing

The generated-parser will try to match the longest piece of text that it can, going in order of the production rules. If we have one production rule (e.g., if/then) that is a prefix of another production rule (e.g., if/then/else), then we should place the longer rule earlier in the grammar. That way, if parsing fails this rule, the parser will try the shorter rule.

Emitting

Use the algorithm we worked out in class to implement conditionals:

  1. Generate labels for the false branch and post-conditional statement
  2. Emit code that evaluates the condition.
  3. Emit code that compares the value of the condition to 0.
  4. Emit code that jumps to the false branch if the value is 0.
  5. Emit code for the true branch.
  6. Emit code to jump to the post-conditional statement.
  7. Emit the false-branch label.
  8. Emit code for the false branch.
  9. Emit the post-conditional label.

4 Loops

Emitting

The implementation for loops can use similar techniques to the implementation for conditionals.